package cn.young.dev.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: Ryan
 * @Date: 2022/1/26 10:11
 * @Description:
 */
public class MysqlConnector {

    private static final String driverClassName = "com.mysql.cj.jdbc.Driver";
    Connection con;

    public MysqlConnector(String url, String userName, String password) throws Exception {
        Class.forName(driverClassName);
        con = DriverManager.getConnection(url, userName, password);
    }

    public List<Map<String, String>>  search(String sql, List<String> fieldList) {
        List<Map<String, String>> list = new ArrayList<>(200);
        if(fieldList == null || fieldList.size() == 0){
            System.out.println("FiledList size is null.");
            return list;
        }
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            Map<String, String> ret = new HashMap<>(1024);
            if (rs == null) {
                return list;
            }
            while (rs.next()) {
                for (int i = 0; i < fieldList.size(); i++) {
                    ret.put(fieldList.get(i), rs.getString(i));
                }
                list.add(ret);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源,倒关
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (con != null) con.close();  //必须要关
            } catch (Exception e) {
                // do nothing
            }
        }
    }
}
